import { Injectable } from '@angular/core';
import { Http, Response,Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
/*
  Generated class for the HttpServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
let apiUrl = 'http://chuangjian.iotplc.cn/';


@Injectable()
export class HttpServiceProvider {

  constructor(public http: Http) {

    console.log('Hello HttpServiceProvider Provider');
  }
  /**
   * 
   * @param credentials 
   */
  login(data) {
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        let options = new RequestOptions({headers: headers});
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.http.post(apiUrl+'Login/login',this.toQueryString(data), options)
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });
  }
  /**
   * 
   * @param data 
   */
  register(data) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      let options = new RequestOptions({headers: headers});
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      this.http.post(apiUrl+'Login/register',this.toQueryString(data), options)
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });
  }
  /**
   * 
   */
  logout(){
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('X-Auth-Token', localStorage.getItem('token'));

        this.http.post(apiUrl+'logout', {}, {headers: headers})
          .subscribe(res => {
            localStorage.clear();
          }, (err) => {
            reject(err);
          });
    });
  }

  getVerCode(telnum){
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      let options = new RequestOptions({headers: headers});
      headers.append('Content-Type', 'application/x-www-form-urlencoded');
      this.http.get(apiUrl+'Login/register/sendCode/'+telnum, options)
        .subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(err);
        });
  });
  }






  get(url:string) {

    return new Promise((resolve, reject) => {
      this.http.get(url)
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        }, err => {
          reject(err);
        })
    })

  }

  post(url:string,body:string) {

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({headers: headers});

    return new Promise((resolve, reject) => {

    this.http.post(url, body ,options)
      .map(res => res.json())
      .subscribe(
         data => resolve(data), err => reject(err)
      )
    })
  }
  /**
   *
   * @param error
   */
  private handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || 'Server Error');
}
  /**
   *
   * @param obj
   */
  private toQueryString(obj) {
    let result = [];
    for (let key in obj) {
      key = encodeURIComponent(key);
      let values = obj[key];
      if (values && values.constructor == Array) {
        let queryValues = [];
        for (let i = 0, len = values.length, value; i < len; i++) {
          value = values[i];
          queryValues.push(this.toQueryPair(key, value));
        }
        result = result.concat(queryValues);
      } else {
        result.push(this.toQueryPair(key, values));
      }
   }
    return result.join('&');
  }



  private toQueryPair(key, value) {
    if (typeof value == 'undefined') {
      return key;
    }
    return key + '=' + encodeURIComponent(value === null ? '' : String(value));
  }


}
